package com.tongtong.config;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tongtong.common.WebConstants;
import com.tongtong.utils.ChannelUtilsV2;
import com.tt.utils.TripleCheckDigitUtil;
import com.ttio.config.TTNettyWebSocket;
import com.ttio.netty.common.Constants;
import com.ttio.netty.utils.ChannelUtils;
import com.ttio.websocket.WebSocketTcpServerSlave;
import com.ttio.websocket.handler.MessageWebSocketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.PostConstruct;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 启动netty socket @author zl
 */
@Slf4j
//@Component
public class WebSocketStartNettyConfig implements MessageWebSocketHandler {
    private Integer port = 40600;

    @PostConstruct
    public void startServer() throws Exception {
        TTNettyWebSocket ttNettyWebSocket = new TTNettyWebSocket(port,this,"/ws");
        ttNettyWebSocket.startNetty();
    }


    @Override
    public void channelAddHandler(ChannelHandlerContext ctx) {
        String key = ChannelUtils.getChannelKey(ctx.channel());
        log.info("用户{}连接成功", key);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, JSONObject jsonObject) {
//        JSONObject jsonObject = JSONUtil.parseObj(maps);
        String key = ChannelUtils.getChannelKey(ctx.channel());
        log.info("发送用户为{},消息内容为{}",key,jsonObject.getJSONObject("data"));
        if (jsonObject.getJSONObject("data").get("type").equals("regist")) {
            ChannelUtils.setChannelExtend(ctx.channel(), jsonObject.getStr("data"));
            WebConstants.userMap.put(key, jsonObject.getJSONObject("data"));
        } else {
            /*推送消息给其他人*/
            Map<String,Object> map = JSONUtil.toBean(jsonObject.toString(), Map.class);
            ChannelUtilsV2.sendRoomOtherChannel(key, map);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        ChannelUtilsV2.UserInfo userInfo = ChannelUtilsV2.queryUserInfoByChannel(ctx.channel());
        ChannelUtilsV2.leaveRoomUser(userInfo);
        String key = ctx.channel().attr(Constants.SessionConfig.KEY).get();
        log.info("用户{}断开连接成功", key);
    }

    @Override
    public boolean loginAuthHandler(Channel channel, FullHttpRequest request) {
        String uri = request.uri();
        String token = getQueryParam(uri, "token");
        log.info("token:" + token);
        return TripleCheckDigitUtil.validateCheckDigits(token);
    }

    /**
     * 从地址中提取参数
     * @param url 请求的地址，例如 "/ws?token=31109025466689115141"
     * @param key 要提取的参数名，例如 "token"
     * @return 参数值，如果不存在返回 null
     */
    public static String getQueryParam(String url, String key) {
        if (url == null || key == null){
            return null;
        }

        int idx = url.indexOf('?');
        if (idx == -1 || idx == url.length() - 1){
            return null;
        }

        String query = url.substring(idx + 1);
        String[] pairs = query.split("&");
        for (String pair : pairs) {
            String[] kv = pair.split("=", 2);
            if (kv.length == 2 && kv[0].equals(key)) {
                return URLDecoder.decode(kv[1], StandardCharsets.UTF_8);
            }
        }

        return null;
    }
}
